package com.ruoyi.project.wx.miniapp.controller;


import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.ruoyi.common.constant.ERPConstant;
import com.ruoyi.common.utils.bean.EmptyUtil;
import com.ruoyi.common.utils.file.MultipartFileToFile;
import com.ruoyi.common.utils.security.JwtTokenUtilHutool;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.erp.attention.domain.ErpAttention;
import com.ruoyi.project.erp.attention.service.IErpAttentionService;
import com.ruoyi.project.erp.goods.domain.ErpGoods;
import com.ruoyi.project.erp.goods.service.IErpGoodsService;
import com.ruoyi.project.erp.member.domain.ErpMember;
import com.ruoyi.project.erp.member.service.IErpMemberService;
import com.ruoyi.project.erp.project.domain.ErpProject;
import com.ruoyi.project.erp.project.service.IErpProjectService;
import com.ruoyi.project.oss.AliyunOSSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;


/**
 * 微信接口Controller
 *
 * @author qinghuan
 * @date 2021-06-24
 */
@Api(tags = "微信接口")
@RequestMapping("/wx")
@RestController
@Slf4j
public class WXController extends BaseController {

    @Autowired
    private IErpMemberService erpMemberService;

    @Autowired
    private JwtTokenUtilHutool jwtTokenUtilHutool;


    @Autowired
    private IErpProjectService erpProjectService;


    @Autowired
    private IErpGoodsService erpGoodsService;


    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;


    @Autowired
    private IErpAttentionService erpAttentionService;


    /**
     * 测试token生成
     *
     * @param memberId
     * @return
     */
//    @ApiOperation(value = "测试token生成")
//    @PostMapping("/testCreateTocken")
//    @ApiOperationSupport(order = 33)
//    public AjaxResult test(Long memberId) {
//
//        ErpMember member = erpMemberService.selectMemberById(memberId);
//        AjaxResult result = AjaxResult.success();
//        result.put("token", jwtTokenUtilHutool.generateToken(member));
//        result.put("member", member);
//        return result;
//    }


//    @ApiOperation(value = "测试token解析")
//    @PostMapping("/testTocken")
//    @ApiOperationSupport(order = 1)
//    public AjaxResult test(Long memberId, String token) {
//
//        //先判断是否过期
//        if (jwtTokenUtilHutool.isTokenExpired(token)) {
//            return AjaxResult.tokenExpired();
//        }
//
//        //判断是用户是否存在
//        ErpMember member = erpMemberService.selectMemberById(memberId);
//        if (EmptyUtil.isEmpty(member)) {
//            return error();
//        }
//
//        //当前用户的token进行校验
//        boolean isTokenSuccess = jwtTokenUtilHutool.validateToken(token, member);
//
//        //如果不匹配则失败
//        if (!isTokenSuccess) {
//            return AjaxResult.tokenFail();
//        }
//
//        //如果匹配则返回信息
//        return success().put("member", member);
//
//    }


    /**
     * 查询所有项目
     */
    @ApiOperation(value = "查询所有项目")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "memberId", dataType = "String", required = true, value = "用户Id"),
            @ApiImplicitParam(paramType = "query", name = "token", dataType = "String", required = true, value = "token"),
            @ApiImplicitParam(paramType = "query", name = "projectName", dataType = "String", required = false, value = "项目名")
    })
    @PostMapping("/projectsList")
//    public AjaxResult projectsList(Long memberId, String token, String projectName ) {
    public AjaxResult projectsList(Long memberId, String token ) {

        if (EmptyUtil.isEmpty(memberId)) {
            return error(ERPConstant.EMPTY_MEMBER_ID);
        }
        if (EmptyUtil.isEmpty(token)) {
            return error(ERPConstant.EMPTY_TOKEN);
        }

        //判断是用户是否存在
        ErpMember member = erpMemberService.selectMemberById(memberId);
        if (EmptyUtil.isEmpty(member)) {
            return error(ERPConstant.EMPTY_MEMBER);
        }
        //当前用户的token进行校验

        //如果不匹配则失败
        if (!jwtTokenUtilHutool.validateToken(token, member)) {
            return AjaxResult.tokenFail();
        }

        if (!(ERPConstant.MEMBER_TYPE_OF_STAFF.intValue() == member.getMemberType().intValue()) &&
                !(ERPConstant.MEMBER_TYPE_OF_MANAGER.intValue() == member.getMemberType().intValue())) {
            return AjaxResult.error("用户类型异常");
        }

        AjaxResult success =  AjaxResult.success();
        ErpAttention erpAttention =  new ErpAttention();
        erpAttention.setStatus(ERPConstant.ATTENTION_STATUS_OF_ON);
        success.put("attentions",erpAttentionService.selectErpAttentionList(erpAttention));
        ErpProject erpProject =   new ErpProject();
//        if (!EmptyUtil.isEmpty(projectName)){
//            erpProject.setProjectName(projectName);
//        }
        success.put("projects",erpProjectService.selectErpProjectList(erpProject));
        return success;

    }


    /**
     * 根据项目id查询顶级明细列表
     */
    @ApiOperation(value = "根据项目id查询顶级明细列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "memberId", dataType = "String", required = true, value = "用户Id"),
            @ApiImplicitParam(paramType = "query", name = "token", dataType = "String", required = true, value = "token"),
            @ApiImplicitParam(paramType = "query", name = "projectId", dataType = "String", required = true, value = "项目id"),
    })
    @PostMapping("/selectParentGoodsByProjectId")
    public AjaxResult selectParentGoodsByProjectId(Long memberId, String token, Long projectId) {

        if (EmptyUtil.isEmpty(memberId)) {
            return error(ERPConstant.EMPTY_MEMBER_ID);
        }
        if (EmptyUtil.isEmpty(token)) {
            return error(ERPConstant.EMPTY_TOKEN);
        }
        if (EmptyUtil.isEmpty(projectId)) {
            return error(ERPConstant.EMPTY_PROJECT_ID);
        }

        //判断是用户是否存在
        ErpMember member = erpMemberService.selectMemberById(memberId);
        if (EmptyUtil.isEmpty(member)) {
            return error(ERPConstant.EMPTY_MEMBER);
        }
        //当前用户的token进行校验

        //如果不匹配则失败
        if (!jwtTokenUtilHutool.validateToken(token, member)) {
            return AjaxResult.tokenFail();
        }

        //判断用户类型，如果不是普通用户和管理员则异常。
        if (!ERPConstant.MEMBER_TYPE_OF_STAFF.equals(member.getMemberType()) &&
                !ERPConstant.MEMBER_TYPE_OF_MANAGER.equals(member.getMemberType())) {
            return AjaxResult.error("用户类型异常");
        }


        AjaxResult success = AjaxResult.success();
        success.put("goodsList",erpGoodsService.selectParentGoodsByProjectId(projectId));

        success.put("totalNum",erpGoodsService.selectTotalNumByProjectId(projectId));

        return success;

    }


    /**
     * 根据图号查询物品
     */
    @ApiOperation(value = "根据图号查询物品")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "memberId", dataType = "Long", required = true, value = "用户Id"),
            @ApiImplicitParam(paramType = "query", name = "token", dataType = "String", required = true, value = "token"),
            @ApiImplicitParam(paramType = "query", name = "goodsId", dataType = "Long", required = true, value = "明细id"),
    })
    @PostMapping("/selectGoodByDrawingNo")
    public AjaxResult selectGoodByDrawingNo(Long memberId, String token, String drawingNo) {

        if (EmptyUtil.isEmpty(memberId)) {
            return error(ERPConstant.EMPTY_MEMBER_ID);
        }
        if (EmptyUtil.isEmpty(token)) {
            return error(ERPConstant.EMPTY_TOKEN);
        }
        if (EmptyUtil.isEmpty(drawingNo)) {
            return error(ERPConstant.EMPTY_GOODS_Draw_NO);
        }

        //判断是用户是否存在
        ErpMember member = erpMemberService.selectMemberById(memberId);
        if (EmptyUtil.isEmpty(member)) {
            return error(ERPConstant.EMPTY_MEMBER);
        }
        //当前用户的token进行校验

        //如果不匹配则失败
        if (!jwtTokenUtilHutool.validateToken(token, member)) {
            return AjaxResult.tokenFail();
        }

        //判断用户类型，如果不是普通用户和管理员则异常。
        if (!ERPConstant.MEMBER_TYPE_OF_STAFF.equals(member.getMemberType()) &&
                !ERPConstant.MEMBER_TYPE_OF_MANAGER.equals(member.getMemberType())) {
            return AjaxResult.error("用户类型异常");
        }
        ErpGoods erpGoods = new ErpGoods();
        erpGoods.setDrawingNo(drawingNo);
        List<ErpGoods> erpGoodsInDb = erpGoodsService.selectErpGoodsList(erpGoods);
        if (EmptyUtil.isEmpty(erpGoodsInDb)){
            return AjaxResult.error("图号不存在");
        }
        return AjaxResult.success(erpGoodsInDb.get(0));

    }



    /**
     * 根据明细id查询子项列表
     */
    @ApiOperation(value = "根据明细id查询子项列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "memberId", dataType = "Long", required = true, value = "用户Id"),
            @ApiImplicitParam(paramType = "query", name = "token", dataType = "String", required = true, value = "token"),
            @ApiImplicitParam(paramType = "query", name = "goodsId", dataType = "Long", required = true, value = "明细id"),
    })
    @PostMapping("/selectGoodsChildrenByGoodsId")
    public AjaxResult selectGoodsChildrenByGoodsId(Long memberId, String token, String goodsId) {

        if (EmptyUtil.isEmpty(memberId)) {
            return error(ERPConstant.EMPTY_MEMBER_ID);
        }
        if (EmptyUtil.isEmpty(token)) {
            return error(ERPConstant.EMPTY_TOKEN);
        }
        if (EmptyUtil.isEmpty(goodsId)) {
            return error(ERPConstant.EMPTY_GOODS_ID);
        }

        //判断是用户是否存在
        ErpMember member = erpMemberService.selectMemberById(memberId);
        if (EmptyUtil.isEmpty(member)) {
            return error(ERPConstant.EMPTY_MEMBER);
        }
        //当前用户的token进行校验

        //如果不匹配则失败
        if (!jwtTokenUtilHutool.validateToken(token, member)) {
            return AjaxResult.tokenFail();
        }

        //判断用户类型，如果不是普通用户和管理员则异常。
        if (!ERPConstant.MEMBER_TYPE_OF_STAFF.equals(member.getMemberType()) &&
                !ERPConstant.MEMBER_TYPE_OF_MANAGER.equals(member.getMemberType())) {
            return AjaxResult.error("用户类型异常");
        }
        ErpGoods erpGoods = new ErpGoods();
        erpGoods.setParentId(goodsId);

        return AjaxResult.success(erpGoodsService.selectErpGoodsList(erpGoods));

    }


    /**
     * 根据明细id查询子项列表
     */
    @ApiOperation(value = "根据明细id更改信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "memberId", dataType = "Long", required = true, value = "用户Id"),
            @ApiImplicitParam(paramType = "query", name = "token", dataType = "String", required = true, value = "token"),
    })
    @PostMapping("/updateGoodsInfoByGoodsId")
    public AjaxResult updateGoodsInfoByGoodsId(Long memberId, String token, ErpGoods erpGoods) {

        if (EmptyUtil.isEmpty(memberId)) {
            return error(ERPConstant.EMPTY_MEMBER_ID);
        }
        if (EmptyUtil.isEmpty(token)) {
            return error(ERPConstant.EMPTY_TOKEN);
        }
        if (EmptyUtil.isEmpty(erpGoods.getGoodsId())) {
            return error(ERPConstant.EMPTY_GOODS_ID);
        }

        //判断是用户是否存在
        ErpMember member = erpMemberService.selectMemberById(memberId);
        if (EmptyUtil.isEmpty(member)) {
            return error(ERPConstant.EMPTY_MEMBER);
        }
        //当前用户的token进行校验

        //如果不匹配则失败
        if (!jwtTokenUtilHutool.validateToken(token, member)) {
            return AjaxResult.tokenFail();
        }

        //判断用户类型，如果不是普通用户和管理员则异常。
        if (!ERPConstant.MEMBER_TYPE_OF_STAFF.equals(member.getMemberType()) &&
                !ERPConstant.MEMBER_TYPE_OF_MANAGER.equals(member.getMemberType())) {
            return AjaxResult.error("用户类型异常");
        }
        int i = erpGoodsService.updateErpGoods(erpGoods);
        if (i > 0) {
            return AjaxResult.success(erpGoods);
        } else {
            return AjaxResult.error(ERPConstant.UPDATE_GOODS_INFO_ERROR);
        }


    }

    /**
     * 根据明细id新增子项
     */
    @ApiOperation(value = "根据明细id更改信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "memberId", dataType = "Long", required = true, value = "用户Id"),
            @ApiImplicitParam(paramType = "query", name = "token", dataType = "String", required = true, value = "token"),
    })
    @PostMapping("/insertGoods")
    public AjaxResult insertGoods(Long memberId, String token, ErpGoods erpGoods) {

        if (EmptyUtil.isEmpty(memberId)) {
            return error(ERPConstant.EMPTY_MEMBER_ID);
        }
        if (EmptyUtil.isEmpty(token)) {
            return error(ERPConstant.EMPTY_TOKEN);
        }

        //判断是用户是否存在
        ErpMember member = erpMemberService.selectMemberById(memberId);
        if (EmptyUtil.isEmpty(member)) {
            return error(ERPConstant.EMPTY_MEMBER);
        }
        //当前用户的token进行校验

        //如果不匹配则失败
        if (!jwtTokenUtilHutool.validateToken(token, member)) {
            return AjaxResult.tokenFail();
        }

        //判断用户类型，如果不是管理员则异常。
        if (!ERPConstant.MEMBER_TYPE_OF_MANAGER.equals(member.getMemberType())) {
            return AjaxResult.error("用户类型异常");
        }
        int i = erpGoodsService.insertErpGoods(erpGoods);
        if (!EmptyUtil.isEmpty(erpGoods.getGoodsId())) {
            return AjaxResult.success(erpGoods);
        } else {
            return AjaxResult.error(ERPConstant.INSERT_GOODS_ERROR);
        }
    }


    /**
     * 根据来源和目的的明细id，实现子项粘贴
     */
    @ApiOperation(value = "根据来源和目的的明细id，实现子项粘贴")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "memberId", dataType = "Long", required = true, value = "用户Id"),
            @ApiImplicitParam(paramType = "query", name = "token", dataType = "String", required = true, value = "token"),
            @ApiImplicitParam(paramType = "query", name = "fromGoodsId", dataType = "Long", required = true, value = "复制来的项目id"),
            @ApiImplicitParam(paramType = "query", name = "toGoodsId", dataType = "Long", required = true, value = "粘贴到的项目id"),
    })
    @PostMapping("/pasteGoodsChildren")
    public AjaxResult pasteGoodsChildren(Long memberId, String token, String fromGoodsId, String toGoodsId) {

        if (EmptyUtil.isEmpty(memberId)) {
            return error(ERPConstant.EMPTY_MEMBER_ID);
        }
        if (EmptyUtil.isEmpty(token)) {
            return error(ERPConstant.EMPTY_TOKEN);
        }
        if (EmptyUtil.isEmpty(fromGoodsId) && EmptyUtil.isEmpty(toGoodsId)) {
            return error(ERPConstant.EMPTY_FROM_OR_TO_ID);
        }

        //判断是用户是否存在
        ErpMember member = erpMemberService.selectMemberById(memberId);
        if (EmptyUtil.isEmpty(member)) {
            return error(ERPConstant.EMPTY_MEMBER);
        }
        //当前用户的token进行校验

        //如果不匹配则失败
        if (!jwtTokenUtilHutool.validateToken(token, member)) {
            return AjaxResult.tokenFail();
        }

        //判断用户类型，如果不是管理员则异常。
        if (!ERPConstant.MEMBER_TYPE_OF_MANAGER.equals(member.getMemberType())) {
            return AjaxResult.error("用户类型异常");
        }


        ErpGoods erpGoods = new ErpGoods();
        erpGoods.setParentId(fromGoodsId);
        //根据物品明细id查询他所有的子集
        List<ErpGoods> erpGoodsChildrenRoot = erpGoodsService.selectErpGoodsList(erpGoods);

        for (int i = 0; i < erpGoodsChildrenRoot.size(); i++) {
            erpGoodsChildrenRoot.get(i).setParentId(toGoodsId);
            erpGoodsService.insertErpGoods(erpGoodsChildrenRoot.get(i));
        }
        return AjaxResult.success();
    }


    /**
     * 根据明细id查询明细数据
     */
    @ApiOperation(value = "根据明细id查询明细数据")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "memberId", dataType = "Long", required = true, value = "用户Id"),
            @ApiImplicitParam(paramType = "query", name = "token", dataType = "String", required = true, value = "token"),
            @ApiImplicitParam(paramType = "query", name = "goodsId", dataType = "Long", required = true, value = "项目id"),
    })
    @PostMapping("/selectGoodsInfoById")
    public AjaxResult selectGoodsInfoById(Long memberId, String token, String goodsId) {

        if (EmptyUtil.isEmpty(memberId)) {
            return error(ERPConstant.EMPTY_MEMBER_ID);
        }
        if (EmptyUtil.isEmpty(token)) {
            return error(ERPConstant.EMPTY_TOKEN);
        }
        if (EmptyUtil.isEmpty(goodsId)) {
            return error(ERPConstant.EMPTY_GOODS_ID);
        }

        //判断是用户是否存在
        ErpMember member = erpMemberService.selectMemberById(memberId);
        if (EmptyUtil.isEmpty(member)) {
            return error(ERPConstant.EMPTY_MEMBER);
        }
        //当前用户的token进行校验

        //如果不匹配则失败
        if (!jwtTokenUtilHutool.validateToken(token, member)) {
            return AjaxResult.tokenFail();
        }

        //判断用户类型，如果不是普通用户和管理员则异常。
        if (!ERPConstant.MEMBER_TYPE_OF_STAFF.equals(member.getMemberType()) &&
                !ERPConstant.MEMBER_TYPE_OF_MANAGER.equals(member.getMemberType())) {
            return AjaxResult.error("用户类型异常");
        }

        return AjaxResult.success(erpGoodsService.selectErpGoodsByGoodsId(goodsId));
    }


    /**
     * 图片专用上传方法
     *
     * @param file
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "图片上传:MultipartFile类型，返回url")
    @PostMapping("/uploadImg")
    @ResponseBody
    public AjaxResult uploadImgFile(Long memberId, String token,MultipartFile file) throws Exception {

        if (EmptyUtil.isEmpty(memberId)) {
            return error(ERPConstant.EMPTY_MEMBER_ID);
        }
        if (EmptyUtil.isEmpty(token)) {
            return error(ERPConstant.EMPTY_TOKEN);
        }


        //判断是用户是否存在
        ErpMember member = erpMemberService.selectMemberById(memberId);
        if (EmptyUtil.isEmpty(member)) {
            return error(ERPConstant.EMPTY_MEMBER);
        }
        //当前用户的token进行校验

        //如果不匹配则失败
        if (!jwtTokenUtilHutool.validateToken(token, member)) {
            return AjaxResult.tokenFail();
        }

        //判断用户类型，如果不是普通用户和管理员则异常。
        if (!ERPConstant.MEMBER_TYPE_OF_STAFF.equals(member.getMemberType()) &&
                !ERPConstant.MEMBER_TYPE_OF_MANAGER.equals(member.getMemberType())) {
            return AjaxResult.error("用户类型异常");
        }

        try {

            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", UUID.fastUUID());
            ajax.put("url", aliyunOSSUtil.upload(MultipartFileToFile.multipartFileToFile(file)));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 视频专用上传方法
     *
     * @param file
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "视频上传：MultipartFile类型视频，返回url")
    @PostMapping("/uploadVideo")
    @ResponseBody
    public AjaxResult uploadVideo(Long memberId, String token,MultipartFile file) throws Exception {

        if (EmptyUtil.isEmpty(memberId)) {
            return error(ERPConstant.EMPTY_MEMBER_ID);
        }
        if (EmptyUtil.isEmpty(token)) {
            return error(ERPConstant.EMPTY_TOKEN);
        }


        //判断是用户是否存在
        ErpMember member = erpMemberService.selectMemberById(memberId);
        if (EmptyUtil.isEmpty(member)) {
            return error(ERPConstant.EMPTY_MEMBER);
        }
        //当前用户的token进行校验

        //如果不匹配则失败
        if (!jwtTokenUtilHutool.validateToken(token, member)) {
            return AjaxResult.tokenFail();
        }

        //判断用户类型，如果不是普通用户和管理员则异常。
        if (!ERPConstant.MEMBER_TYPE_OF_STAFF.equals(member.getMemberType()) &&
                !ERPConstant.MEMBER_TYPE_OF_MANAGER.equals(member.getMemberType())) {
            return AjaxResult.error("用户类型异常");
        }

        log.info("=========>文件上传");
        String uploadUrl = "";
        try {
            if (null != file) {
                String filename = file.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    uploadUrl = aliyunOSSUtil.upload(MultipartFileToFile.multipartFileToFile(file));
                    log.info(uploadUrl);
                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return  AjaxResult.success(uploadUrl);
    }


}
